/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

   TCPSyncPacketExchangeTest.cpp. Created on: 28.10.2009 17:00:16 
*/

#include "cpputils/TestUtils.hpp"
#include "TestTCPClient.hpp"
#include "TestTCPServer.hpp"

class PerfListener : public IStreamListener {
public:
	boost::condition m_evAwait;
	boost::mutex m_mxMonitor;
	unsigned int m_nRcvdCnt, m_nRcvdBytes;

	PerfListener(): m_nRcvdCnt(0), m_nRcvdBytes(0) {}

	virtual void onReceived(IConnection* poConnection, cpputils::io::ByteBuffer* poBuffer) throw() {
		boost::unique_lock<boost::mutex> oLock(m_mxMonitor);
		m_nRcvdCnt++;
		m_nRcvdBytes+=poBuffer->getLenFromPos();
		m_evAwait.notify_one();
	}

	virtual void onReceiveError(IConnection* poConnection, const std::string& sErrorMessage) throw() {}
	virtual void onWriteError(IConnection* poConnection, const std::string& sErrorMessage) throw() {}

};

class ServerEchoListener : public IStreamListener {
public:
	virtual void onReceived(IConnection* poConnection, cpputils::io::ByteBuffer* poBuffer) throw() {
		try {
			poConnection->send(poBuffer);
		}
		catch(const std::exception& ex) {
			std::cout << " Exception: " << ex.what() <<std::endl;
		}
	}

	virtual void onReceiveError(IConnection* poConnection, const std::string& sErrorMessage) throw() {}
	virtual void onWriteError(IConnection* poConnection, const std::string& sErrorMessage) throw() {}
};


BOOST_AUTO_TEST_CASE ( TestSyncPacketExchange ) {
	boost::intrusive_ptr<URI> poServerURI  ( new URI("tcp://localhost:3333") , false );

	TestTCPServer::SharedPtr poServer (
			new TestTCPServer( poServerURI.get())
	);

	TestTCPClient::SharedPtr poClient (
			new TestTCPClient( poServerURI.get() )
	);

	poServer->start();

	boost::mutex::scoped_lock oLock ( poClient->getConnectionListener().getMonitor()) ;
	boost::mutex::scoped_lock oServerLock ( poServer->getAcceptorListener().getMonitor() );
	poClient->start();
	poServer->getAcceptorListener().waitForAnyEvent(oServerLock);
	oServerLock.unlock();
	poClient->getConnectionListener().waitForAnyEvent(oLock);
	oLock.unlock();

	poClient->getConnector()->delConnectionListener(&poClient->getConnectionListener());
	poClient->getConnector()->delStreamListener(&poClient->getConnectionListener());
	IConnection* poAcceptorConnection  = poServer->getAcceptorListener().getConnections().front();

	poAcceptorConnection->delConnectionListener(&poServer->getAcceptorListener().getConnectionListener());
	poAcceptorConnection->delStreamListener(&poServer->getAcceptorListener().getConnectionListener());

	ServerEchoListener oEchoListener;
	poAcceptorConnection->addStreamListener(&oEchoListener);

	PerfListener oPerfListener;
	poClient->getConnector()->addStreamListener(&oPerfListener);

	const unsigned char aBuffer[] =  { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
	ByteBuffer oBuffer( sizeof(aBuffer) );
	oBuffer.append(aBuffer, sizeof(aBuffer));

	const unsigned int PRF_ITER_SYNC_CNT = 100000;
	time_t nStartTime, nEndTime, nProgressTime1, nProgressTime2;
	nStartTime = time(NULL);
	nProgressTime1 = nStartTime;
	nProgressTime2 = nStartTime;

	unsigned long nSntBytes = 0, nTps = 0,
			nMaxTps = 0, nMinTps = (unsigned long)-1, nMidTps = 0,
			nTotalSent = 0, nTotalRcvd = 0;

	for(unsigned int i = 0; i < PRF_ITER_SYNC_CNT; i++, nTps++) {
		boost::unique_lock<boost::mutex> oLock(oPerfListener.m_mxMonitor);
		poClient->getConnector()->send(&oBuffer);
		oPerfListener.m_evAwait.wait(oLock);
		nProgressTime1 = time(NULL);
		nSntBytes+=oBuffer.getLenFromPos();
		nTotalSent+=oBuffer.getLenFromPos();
		if(nProgressTime1 > nProgressTime2 + 1) {
			BOOST_MESSAGE ( (boost::format("TPS/RCVD: %1% / %2%. Bytes: %3% / %4%") %nTps %oPerfListener.m_nRcvdCnt %nSntBytes %oPerfListener.m_nRcvdBytes ).str() );
			nTotalRcvd+=oPerfListener.m_nRcvdBytes;
			oPerfListener.m_nRcvdCnt = 0;
			oPerfListener.m_nRcvdBytes = 0;
			nSntBytes=0;
			nProgressTime2 = nProgressTime1;

			if(nMaxTps < nTps) {
				nMaxTps = nTps;
			}
			if(nMinTps > nTps && i > PRF_ITER_SYNC_CNT / 10) {
				nMinTps = nTps;
			}
			nMidTps+=nTps;
			nTps = 0;
		}

	}

	nEndTime = time(NULL);

	poClient->stop();
	poServer->stop();
}
